<?php

namespace app\adminweixin\controller;

use think\Controller;
use think\exception\HttpException;

/**
 * 小程序API基础控制器
 */
class Api extends Controller
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];
    
    public function _initialize()
    {
        parent::_initialize();
        
        // 设置跨域
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization');
        
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit();
        }
        
        // 设置响应格式
        $this->response->type('json');
    }
    
    /**
     * 成功响应
     */
    protected function success($data = null, $msg = '操作成功', $code = 1)
    {
        return json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
            'timestamp' => time()
        ]);
    }
    
    /**
     * 错误响应
     */
    protected function error($msg = '操作失败', $code = 0, $data = null)
    {
        return json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
            'timestamp' => time()
        ]);
    }
    
    /**
     * 获取请求参数
     */
    protected function getParam($key, $default = null)
    {
        return $this->request->param($key, $default);
    }
    
    /**
     * 获取POST参数
     */
    protected function getPost($key, $default = null)
    {
        return $this->request->post($key, $default);
    }
    
    /**
     * 获取GET参数
     */
    protected function getGet($key, $default = null)
    {
        return $this->request->get($key, $default);
    }
} 